<?php
    //////////////////////////////CALCULATE VALUE - DISCOUNT - SAVE - VALUE AFTER DISCOUNT///////////////////////////////////////
    if(is_admin() && $_GET['post_type'] != 'store')
    {
        add_action('admin_footer', 'admin_deal_scripts');
        add_action('admin_footer','add_deal_masklink'); 
        add_action('admin_footer','ASDFASDF');
        // Callback function
        add_action('wp_ajax_add_mask_action','add_masklinks_deal');
        add_action('wp_ajax_process_html','asasdadsd');
    }
	function admin_deal_scripts()
	{ ?>
    <script type="text/javascript">    
        jQuery(document).ready(function($)
        {            
            $('#value_metadata').on('keyup blur change', function(){
                cal_value();                
            });
            $('#discount_metadata').on('keyup blur change', function(){
                cal_value();                
            });
            $('#after_discount_metadata').on('keyup blur change', function(){
                cal_value();                
            });
            
            function cal_value()
            {
                var value = parseInt($('#value_metadata').val());
                var discount = parseInt($('#discount_metadata').val());
                
                var vl_after = value - ((value*discount)/100);
                var saved = value - vl_after;
                
                $('#after_discount_metadata').val(vl_after);
                $('#save_metadata').val(saved);
            }
        })
    </script>
<?php 
    }
    ///////////////////////////////ADD DEAL MASK LINK/////////////////////////////////////////////////
    function add_deal_masklink()
    { ?>        
        <script type="text/javascript">    
        jQuery(document).ready(function($)
        {
            /**
             * ADD BUTTON SUBMIT
             */
            var btn = "<div id='submit_area' style='margin:10px'><input type='button' value='Submit links' class='button button-primary button-small' id='cpx_submit_dealmasklink' /></div>";            
            var btn_clear = "<input style='margin-left:10px' type='button' value='Remove all' class='button button-primary button-small' id='cpx_clear' />";
            
            $('#box_extra_metadata').append(btn);
            $('#submit_area').append(btn_clear + "<br/>");
            /**
             * ADD MASK LINK
             */
            //button clear
            $('input[id="cpx_clear"]').click(function(){
                $('#extra_metadata').val('');
            });
            // button submit
            $('input[id="cpx_submit_dealmasklink"]').click(function(){
                // add loading circle
                $('#submit_area').append("<?php css_loading(1); ?>");
                
                var post_id = $('input[id="post_ID"]').val();
                var l1 = $('#extra_metadata').val();
                
                var sending_data = new Array(); 
                sending_data[0] = post_id;
                sending_data[1] = l1;
                
                var data = {
                    action:'add_mask_action',
                    value:sending_data
                };
                $.post(ajaxurl, data, function(rs) {
                    $('#circularG').remove();
                    alert("Success! Added " + rs + " links");
                    $('#post').submit();
                });
                // stop submit to test
                //return false;
            });
        })
        </script>  
    <?php
    }
    
    function add_masklinks_deal()
    {
        // get sending values
        $vl = $_POST['value'];
        $post_id = $vl[0];
        // get extra link
        $l1 = $vl[1];
        
        $arr = array();
        // push extra links to array
        if($l1)
        {
            $arr_extra_links = explode(';', $l1);
            // if multi extra links
            if(count($arr_extra_links) > 0)
            {
                foreach ($arr_extra_links as $links) {
                    $l = explode('|', $links);
                    $l = trim($l[count($l) - 1]);
                    if($l != '')
                        array_push($arr, $l);
                }
            }
            // if 1 extra link
            else
            {
                $link = explode('|', $l1);
                $l = $link[count($link) - 1];
                if($l != '')
                    array_push($arr, $l);
            }
        }
        if(count($arr) > 0)
        {
            foreach ($arr as $k => $v)
            {
                if(metadata_exists('post', $post_id, 'l'.$k))
                {
                    update_post_meta($post_id, 'l'.$k, $v);                    
                    for($i = count($arr); $i < 40; $i++)
                    {
                        delete_post_meta($post_id, 'l'.$i);
                    }
                }
                else
                    add_post_meta($post_id, 'l'.$k, $v, true);
            }
        }
        else
        {
            for($i = count($arr); $i < 40; $i++)
            {
                delete_post_meta($post_id, 'l'.$i);
            }
        }
        echo count($arr);
        die();
    }
    //////////////////////////////////////////PROCESS XML///////////////////////////////////////////////////
    function css_loading($display_with_btnsubmitlinks = 0)
    { 
        if($display_with_btnsubmitlinks == 0)
            echo "<div id='circularG'><div id='circularG_1' class='circularG'></div><div id='circularG_2' class='circularG'></div><div id='circularG_3' class='circularG'></div><div id='circularG_4' class='circularG'></div><div id='circularG_5' class='circularG'></div><div id='circularG_6' class='circularG'></div><div id='circularG_7' class='circularG'></div><div id='circularG_8' class='circularG'></div></div>";
        else if($display_with_btnsubmitlinks == 1)
            echo "<div id='circularG' style='margin-left:28px'><div id='circularG_1' class='circularG'></div><div id='circularG_2' class='circularG'></div><div id='circularG_3' class='circularG'></div><div id='circularG_4' class='circularG'></div><div id='circularG_5' class='circularG'></div><div id='circularG_6' class='circularG'></div><div id='circularG_7' class='circularG'></div><div id='circularG_8' class='circularG'></div></div>";            
    }
    function ASDFASDF()
    { ?>        
        
        <script type="text/javascript">    
        jQuery(document).ready(function($)
        {
            //toogle link
            var tog = "<hr/><a style='cursor:pointer;margin-left:10px' id='avangate' name='avangate'>Read XML from Affiliate Market &#x25BC;</a><br/><br/>";
            
            var txt = "<div style='display:none;padding:10px' name='market_area' id='market_area'>";
            var btn_process = "<input style='margin-top:5px' type='button' value='Process' class='button button-primary button-small' id='cpx_processxml' />";
            var chk_sort = "<div style='margin-top:3px;margin-left:1px'><input type='checkbox' id='chk'/>Sort by Price ASC</div><br/>";
            var browse_file = "<input placeholder='XML url' type='text' name='file' id='file' style='width:600px' />";            
            var coupon = "<input type='text' placeholder='Coupon Code' name='cp' id='cp'/>";
            var remove_link = "<a style='cursor:pointer;font-size:11px' id='rm' name='rm'>Remove Coupon</a>";            
            
            var div_result = "<div id='links_result' name='links_result' style='margin-top:10px;line-height:20px;background-color:whitesmoke;padding:2px'></div>";
            var sl_network = "<select style='margin-top:-3px' id='sl_nw' name='sl_nw'><option value='av'>Avangate</option><option value='rn'>Regnow</option></select>";
            
            txt += sl_network;
            txt += browse_file + "<br/>";
            txt += coupon + remove_link + "<br/>";
            txt += chk_sort;
            
            txt += btn_process + "<div id='loading' name = 'loading' style='display:inline-block;margin-top:5px;margin-left:5px'></div>" + "<br/>";
            txt += div_result;
            txt += "</div>";
            $('#box_extra_metadata').append(tog);
            $('#box_extra_metadata').append(txt);       
            
            // Toogle event
            $('#avangate').click(function(){
                $('#market_area').toggle();
            });
            // remove coupon code
            $('#rm').click(function(){
                $('#cp').val('');
            });
            // button process
            $('#cpx_processxml').click(function(){
                // display loading circle
                $('#loading').append("<?php css_loading(); ?>");
                // clear old html
                $('#links_result').empty();
                
                var xml_url = $('#file').val();
                var arr = new Array();
                arr[0] = xml_url;
                arr[1] = $('#sl_nw').val();
                arr[2] = $('#cp').val();
                arr[3] = $('#chk').is(':checked');
                
                var data = {
                    action:'process_html',
                    value:arr
                };
                $.post(ajaxurl, data, function(rs) {
                    //remove loading circle
                    $('#loading').empty();
                    
                    rs = $.parseJSON(rs);
                    $.each(rs, function (k, v) {                        
                        var a = (k+1) + ". <a class='ver_aff' style='cursor:pointer' title='" + v.aff + "'>" + v.name + "|" + v.price + "</a><br/>";
                        $('#links_result').append(a);
                        if(k == rs.length - 1)
                            $('#links_result').append("<hr/>");                           
                    });
                     
                });
            });
            // onclick on return versions
            $('#market_area').on('click','.ver_aff',function(){
                t = $(this).text() + "|" + $(this).attr('title') + ";";
                // check if color = red => clicked
                if($(this).css('color') == 'rgb(255, 0, 0)')
                {
                    $(this).css('color','rgb(46, 162, 204)');
                    var removed = $('#extra_metadata').val().replace(t,' ');
                    $('#extra_metadata').val($.trim(removed));
                }
                // not click
                else if($(this).css('color') == 'rgb(46, 162, 204)')
                {                    
                   // append text to textarea
                   $('#extra_metadata').val($('#extra_metadata').val() + t);
                   $(this).css('color','red');  
                }
            });
        })
        </script>
    <?php
    }
    
    function asasdadsd()
    {
        $vls = $_POST['value'];
        $xml_url = $vls[0];
        $sl_aff = $vls[1];
        $cp = $vls[2];
        $sort = $vls[3];
        
        if($xml_url != '')
        {
            if($sl_aff == 'av')
            {
                $arr = cpx_read_xml($xml_url, 'avangate', $cp, $sort);
                //return json array
                $arr = json_encode((array)$arr);
                echo $arr;
                die();
            }
            else if($sl_aff == 'rn')
            {
                $arr = cpx_read_xml($xml_url, 'regnow', $cp, $sort);
                //return json array
                $arr = json_encode((array)$arr);
                echo $arr;
                die();
            }
        }
    }
    /**
     * DISABLE SOME ELEMENTS IF NOT ADMIN
     */
    if(cpx_get_user_role_name() != 'administrator')
    {
        add_action('admin_head','not_allow');
    }
    function not_allow()
    { ?>
        <script type="text/javascript">    
        jQuery(document).ready(function($)
        {
            $('#box_mainlink_metadata,#box_deal_metadata,#box_extra_metadata').hide();
        })
        </script>
    <?php
    }
?>